package com.javastar.common.resolver;

import com.javastar.common.annotation.LoginUser;
import com.javastar.common.enums.TokenEnum;
import com.javastar.common.utils.JwtUtil;
import com.javastar.modules.user.entity.UserEntity;
import com.javastar.modules.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserEntity.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        // 从request中获取用户ID - 已经被@Login解析过
        Object objectId = request.getAttribute("userId", RequestAttributes.SCOPE_REQUEST);
        if (objectId != null) {
            return userService.getById((Long) objectId);
        }

        // 从header的token中获取用户信息 - 未标注@Login
        // 从header中获取token
        String userToken = request.getHeader(TokenEnum.USER_TOKEN.getTokenKey());

        // 用户id
        com.javastar.common.bean.LoginUser loginUser;

        // token为空
        if (StringUtils.isBlank(userToken)) {
            return null;
        }

        // token无效
        if (!JwtUtil.validateToken(userToken, TokenEnum.USER_TOKEN) || (loginUser = JwtUtil.getBean(userToken, TokenEnum.USER_TOKEN, com.javastar.common.bean.LoginUser.class)) == null) {
            return null;
        }

        // 返回用户信息
        return userService.getById(loginUser.getId());
    }
}
